package com.microlecture.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.microlecture.common.Constants;
import com.microlecture.common.DataPacket;
import com.microlecture.entity.Cookbook;
import com.microlecture.entity.CookbookCollect;
import com.microlecture.mapper.CookbookCollectMapper;
import com.microlecture.service.CookbookCollectService;
import com.microlecture.service.CookbookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CookbookCollectServiceImpl implements CookbookCollectService {

    @Autowired
    private CookbookCollectMapper cookbookCollectMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return cookbookCollectMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insertSelective(CookbookCollect record) {
        return cookbookCollectMapper.insertSelective(record);
    }

    @Override
    public CookbookCollect selectByPrimaryKey(Integer id) {
        return cookbookCollectMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(CookbookCollect record) {
        return cookbookCollectMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public List<CookbookCollect> selectByCondition(Integer userid, Integer cookbookid) {
        return cookbookCollectMapper.selectByCondition(userid, cookbookid);
    }

    @Autowired
    private CookbookService cookbookService;

    @Override
    public Map<String, Object> selectByCondition(int page, int rows, Integer userid) {
        Page<CookbookCollect> paging = PageHelper.startPage(page, rows);
        List<Cookbook> list = new ArrayList<>();
        List<CookbookCollect> cookbookCollects = cookbookCollectMapper.selectByCondition(userid, null);
        for(CookbookCollect cookbookCollect : cookbookCollects) {
            Cookbook cookbook = cookbookService.selectByPrimaryKey(cookbookCollect.getCookbookid());
            list.add(cookbook);
        }
        Map<String, Object> result = DataPacket.dataGridResult(paging.getTotal(), list);
        result.put("currentPage", paging.getPageNum());
        result.put("totalPage", (int) Math.ceil(Double.valueOf(paging.getTotal()) / Constants.pageSize));
        result.put("page", paging);
        return result;
    }
}